// 账户体系模块-mysql服务处理

// 引入数据库模块
const db = require('../config/mysql.js')
const utils = require("../common/utils")
const bcrypt = require('bcryptjs')
// 引入jwt
const jwt = require('jsonwebtoken')
const secretKey = 'ethink'    // 密钥

// 存储验证码
const setQrCode = (email, qrcode) => {
  return new Promise((resolve, reject) => {
    db.query(`select email from code where email = "${email}"`, (err, result) => {
      if (err) return reject(err)
      if (result.length > 0) {
        let sql = `update code set code = ${qrcode} where email = "${email}"`
        db.query(sql, (err1, res) => {
          if (err1) return reject(err1)
          if (res.affectedRows === 1) return resolve(true)
          return resolve(false)
        })
      } else {
        let sql = `insert into code(email,code) values("${email}", "${qrcode}")`
        db.query(sql, (err2, res) => {
          if (err2) return reject(err2)
          if (res.affectedRows === 1) return resolve(true)
          return resolve(false)
        })
      }
    })    
  })
}

// 获取验证码
const getQrCode = (email) => {
  return new Promise((resolve, reject) => {
    let sql = `select code from code where email = "${email}"`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      if (result.length == 1) {
        let qrcode = result[0].code
        return resolve(qrcode)
      } else {
        return resolve()
      }
    })
  })
}

// 注册
const register = (email, password) => {
  let uuid = `167${utils.randomNumber()}${utils.randomNumber()}`
  let register_time = utils.formatDate(new Date().getTime())
  return new Promise((resolve, reject) => {
    db.query(`select email from user where email = "${email}"`, (err, result) => {
      if (err) return reject(err)
      if (result.length >= 1) return resolve("邮箱已被注册")
      // 邮箱不存在
      password = bcrypt.hashSync(password, 10)
      let sql = `insert into user (id, email, password, register_time) values(?,?,?,?)`
      db.query(sql, [uuid, email, password, register_time], (err1, res) => {
        if (err1) return reject(err1)
        if (res.affectedRows == 1) return resolve("注册成功")
      })
    })
  })
}

// 登录
const login = (email, password) => {
  return new Promise((resolve, reject) => {
    db.query(`select * from user where email = "${email}"`, (err, result) => {
      if (err) return reject(err)
      if (result.length == 0) return reject("邮箱不存在，请先注册")
      if (result.length == 1) {
        // 密码比对
        let compareResult = bcrypt.compareSync(password, result[0].password)
        if (!compareResult) return reject('密码错误，请重新输入')
        // 是否被禁用
        if (result[0].status) {
          // token生成
          db.query(`select role_name, index_page from role where id = "${result[0].role_id}"`, (err1, result1) => {
            if (err1) return reject(err1)
            if (result1.length == 1) {
              const userInfo = {...result[0]}
              userInfo.role_name = result1[0].role_name
              delete userInfo.password
              delete userInfo.status
              let token = jwt.sign(userInfo, secretKey, {expiresIn: '7d'})
              return resolve({
                token,
                indexPath: result1[0].index_page
              })
            }
            return reject('登录失败')
          })
        } else {
          return reject('该用户已被禁用，请联系管理员')
        }
      }
    })
  })
}

module.exports = {
  setQrCode,
  getQrCode,
  register,
  login
}